var isDesktop = navigator['userAgent'].match(/(ipad|iphone|ipod|android|windows phone)/i) ? false : true;
var fontunit = isDesktop ? 20 : ((window.innerWidth > window.innerHeight ? window.innerHeight : window.innerWidth) / 320) * 10;
document.write('<style type="text/css">' +
	'html,body {font-size:' + (fontunit < 30 ? fontunit : '30') + 'px;}' +
	(isDesktop ? '#welcome,#GameLayerBG,#GameScoreLayer.SHADE{position: absolute;}' :
	'#welcome,#GameTimeLayer,#GameLayerBG,#GameScoreLayer.SHADE{position:fixed;}') +
	'</style>');
if (isDesktop)
		document.write('<div id="gameBody">');
	var body, blockSize, GameLayer = [], GameLayerBG, touchArea = [], GameTimeLayer;
	var transform, transitionDuration;
	function init (argument) {
		body = document.getElementById('gameBody') || document.body;
		body.style.height = window.innerHeight+'px';
		transform = typeof(body.style.webkitTransform) != 'undefined' ? 'webkitTransform' : (typeof(body.style.msTransform) != 'undefined'?'msTransform':'transform');
		transitionDuration = transform.replace(/ransform/g, 'ransitionDuration');

		GameTimeLayer = document.getElementById('GameTimeLayer');
		GameLayer.push( document.getElementById('GameLayer1') );
		GameLayer[0].children = GameLayer[0].querySelectorAll('div');
		GameLayer.push( document.getElementById( 'GameLayer2' ) );
		GameLayer[1].children = GameLayer[1].querySelectorAll('div');
		GameLayerBG = document.getElementById( 'GameLayerBG' );
		if( GameLayerBG.ontouchstart === null ){
			GameLayerBG.ontouchstart = gameTapEvent;
		}else{
			GameLayerBG.onmousedown = gameTapEvent;
		}
		gameInit();
		window.addEventListener('resize', refreshSize, false);

		var rtnMsg = "true";	
				
		setTimeout(function(){
		    if (rtnMsg) {
		        $("#gameStart").hide();
		        var l = document.getElementById('welcome');
		        l.style.display = 'block';

				var btn = document.getElementById('ready-btn');

                    btn.onclick = function(){
                        if($("#ready-btn").attr("jumpurl")!='') {
                            location.href=$("#ready-btn").attr("jumpurl");
                        }else{
                            closeWelcomeLayer();
                            $(".cover").show();
                            setTimeout(function(){
                                $(".cover").hide();
                            },3000);
                            $(".word").removeClass("hide")
                            $(".word").addClass("fadeOut")
                            $(".word").html('<div class="fadeOut" style="position: fixed;bottom:0;font-size:20px;font-weight:700;color:#FDF34B;margin-top:20%;left:30%;width20%;"><p>点击下方第一个脚印</p></div>');

                    }
                }

			}					
		}, 1200);
	}
	var refreshSizeTime;
	function refreshSize(){
		clearTimeout(refreshSizeTime);
		refreshSizeTime = setTimeout(_refreshSize, 200);
	}
	function _refreshSize(){
		countBlockSize();
		for( var i=0; i<GameLayer.length; i++ ){
			var box = GameLayer[i];
			for( var j=0; j<box.children.length; j++){
				var r = box.children[j],
					rstyle = r.style;
				rstyle.left = (j%4)*blockSize+'px';
				rstyle.bottom = Math.floor(j/4)*blockSize+'px';
				rstyle.width = blockSize+'px';
				rstyle.height = blockSize+'px';
			}
		}
		var f, a;
		if( GameLayer[0].y > GameLayer[1].y ){
			f = GameLayer[0];
			a = GameLayer[1];
		}else{
			f = GameLayer[1];
			a = GameLayer[0];
		}
		var y = (_gameBBListIndex%10)*blockSize;
		f.y = y;
		f.style[transform] = 'translate3D(0,'+f.y+'px,0)';

		a.y = -blockSize*Math.floor(f.children.length/4)+y;
		a.style[transform] = 'translate3D(0,'+a.y+'px,0)';

	}
	function countBlockSize(){
		blockSize = body.offsetWidth*0.91/4;
		body.style.height = window.innerHeight+'px';
		GameLayerBG.style.height = window.innerHeight+'px';
		touchArea[0] = window.innerHeight-blockSize*1;
		touchArea[1] = window.innerHeight-blockSize*2;
	}
	var _gameBBList = [], _gameBBListIndex = 0, _gameOver = false, _gameStart = false, _gameTime, _gameTimeNum, _gameScore;
	var _gameStageList = [], _gameStageIndex = 0, timer, _redxinMax = 5;
	function gameInit(){
	    createjs.Sound.registerSound({ src: "/app/Game/Static/audio/dingzi.mp3", id: "dingzi" });
	    createjs.Sound.registerSound({ src: "/app/Game/Static/audio/hongxin.mp3", id: "hongxin" });
	    createjs.Sound.registerSound({ src: "/app/Game/Static/audio/jiaoyin.mp3", id: "jiaoyin" });
	    createjs.Sound.registerSound({ src: "/app/Game/Static/audio/shitou.mp3", id: "shitou" });
	    createjs.Sound.registerSound({ src: "/app/Game/Static/audio/zhangliang.mp3", id: "zhangliang" });
		gameRestart();
	}
	function gameRestart(){
		_gameBBList = [];
		_gameBBListIndex = 0;

		_gameStageList = [];
		_gameStageIndex = 0;
		_redxinMax = 5;

		_gameScore = 0;
		_gameOver = false;
		_gameStart = false;
		_gameTimeNum = 3000;
		GameTimeLayer.innerHTML = creatTimeText(_gameTimeNum);
		countBlockSize();
		refreshGameLayer(GameLayer[0]);
		refreshGameLayer(GameLayer[1], 1);
	}
	function gameStart(){
		$(".word").addClass("hide")
		_gameStart = true;
		_gameTime = setInterval(gameTime, 10);
	}
	function gameTime(){
		_gameTimeNum --;
		if( _gameTimeNum <= 0){
			GameTimeLayer.innerHTML = "0'00''";
			$('#timeOver').removeClass("hide");
			NoStopCtrl.gameOver();
			GameLayerBG.className += ' flash';
			createjs.Sound.play("hongxin");
		}else{
			GameTimeLayer.innerHTML = creatTimeText(_gameTimeNum);
		}
	}
	function creatTimeText( n ){
		var text = (100000+n+'').substr(-4,4);
		text = text.substr(0, 2) + "'" + text.substr(2) + "''";
		return text;
	}
	var _ttreg = / t{1,2}(\d+)/, _clearttClsReg = / t{1,2}\d+| bad/,_clears1ClsReg = / s\d/;
	function refreshGameLayer( box, loop, offset ){
		var i = Math.floor(Math.random()*1234)%4+(loop?0:4);
		for( var j=0; j<box.children.length; j++){
			var r = box.children[j],
			rstyle = r.style;
			rstyle.left = (j%4)*blockSize+'px';
			rstyle.bottom = Math.floor(j/4)*blockSize+'px';
			rstyle.width = blockSize+'px';
			rstyle.height = blockSize+'px';
			r.className = r.className.replace(_clearttClsReg, '');
			r.className = r.className.replace(_clears1ClsReg, '');
			if (i == j) {
                //脚印
			    _gameBBList.push({ cell: i % 4, id: r.id });
               
				var random=i%4>=2? 1:0;
				r.className += ' t'+random;

				var random1=Math.floor((Math.random()*1234)%4);
                //道具
				if( loop ){
					var x=j%4;
					if (random1 != x) {
					    var endNum = Math.floor(j / 4) * 4 + random1;
					    var stageType = randomStage();
					    box.children[endNum].className = box.children[endNum].className + ' s' + stageType;
					    _gameStageList.push({ cell: i % 4, id: box.children[endNum].id, type: stageType });
					} else {
					    _gameStageList.push({ cell: -1, id: '', type: '' });
					}
				}else{
					if(j>7){
						var x=j%4;
						if(random1!=x)
						{
						    var endNum = Math.floor(j / 4) * 4 + random1;
						    var stageType = randomStage();
						    box.children[endNum].className = box.children[endNum].className + ' s' + stageType;
							_gameStageList.push({ cell: i % 4, id: box.children[endNum].id, type: stageType });
						} else {
						    _gameStageList.push({ cell: -1, id: '', type: '' });
						}
					} else {
					    _gameStageList.push({ cell: -1, id: '', type: '' });
					}
				}
				r.notEmpty = true;
				i = ( Math.floor(j/4)+1)*4+Math.floor((Math.random()*1234)%4);

			}else{
				r.notEmpty = false;
			}
		}
		if( loop ){
			box.style.webkitTransitionDuration = '0ms';
			box.style.display          = 'none';
			box.y                      = -blockSize*(Math.floor(box.children.length/4)+(offset||0))*loop;
			setTimeout(function(){
				box.style[transform] = 'translate3D(0,'+box.y+'px,0)';
				setTimeout( function(){
					box.style.display     = 'block';
				}, 100 );
			}, 200 );
		} else {
			box.y = 0;
			box.style[transform] = 'translate3D(0,'+box.y+'px,0)';
		}
		box.style[transitionDuration] = '150ms';
	}
	function gameLayerMoveNextRow(){
		for(var i=0; i<GameLayer.length; i++){
			var g = GameLayer[i];
			g.y += blockSize;
			if( g.y > blockSize*(Math.floor(g.children.length/4)) ){
				refreshGameLayer(g, 1, -1);
			}else{
				g.style[transform] = 'translate3D(0,'+parseInt(g.y)+'px,0)';
			}
		}
	}

	function randomStage() {
	    var stageType = Math.floor((Math.random() * 1234) % 8);
	    if (stageType > 3 || (stageType == 3 && _redxinMax <= 0)) {
	        stageType = Math.floor((Math.random() * 1234) % 3);
	    } 
	    if (stageType == 3) {
	        _redxinMax--;
	    }
	    return stageType;
	}
	function gameTapEvent(e){
		if (_gameOver) {
			return false;
		}
		var tar = e.target;
		var y = e.clientY || e.targetTouches[0].clientY,
			x = (e.clientX || e.targetTouches[0].clientX)-body.offsetLeft,
			cha=body.offsetWidth*0.95;
			x=x+cha;
			p = _gameBBList[_gameBBListIndex];
		if ( y > touchArea[0] || y < touchArea[1]) {
			return false;
		}
		if( (p.id==tar.id&&tar.notEmpty) || (p.cell==0&&x<blockSize+cha) || (p.cell==1&&x>blockSize+cha&&x<2*blockSize+cha) || (p.cell==2&&x>2*blockSize+cha&&x<3*blockSize+cha) || (p.cell==3&&x>3*blockSize+cha) ){
			if( !_gameStart ){
				gameStart();
			}
        	createjs.Sound.play("jiaoyin");
        	tar = document.getElementById(p.id);
        	tar.className = 'block tt0';
        	k = _gameStageList[_gameStageIndex];
        	if (k.id != '') {
        	    var tar1 = document.getElementById(k.id);
        	    tar1.className = 'block tt0';
        	}
			_gameBBListIndex++;
			_gameStageIndex++;
			$("#stageShow").hide();
			_gameScore += 1;
			clearTimeout(timer);
			document.getElementById("stageShow").className = 'stageS1 stageShow';
			$("#stageShow").show();
			$('#number span').html(_gameScore+"步");
			timer = setTimeout(function () { document.getElementById("stageShow").className = "" },500);
			gameLayerMoveNextRow();
		} else if (_gameStart && !tar.notEmpty && / s\d/.test(tar.className)) {
		    tar.className = 'block tt0';
			var tar1 = document.getElementById(p.id);
			tar1.className = 'block tt0';
			k = _gameStageList[_gameStageIndex];
			clearTimeout(timer);
			switch (k.type) {
			    case 0://石头-+/-（随机）5s Math.floor((Math.random() * 1234) % 4)
			        // var kes = Math.floor((Math.random() * 1234) % 6);
			        // if (kes <2) {
			        //     _gameTimeNum += 500;
			        //     document.getElementById("stageShow").className = 'stageS3 stageShow';
			        // } else {
			            _gameTimeNum -= 500;
			            document.getElementById("stageShow").className = 'stageS4 stageShow';
			       // }
			        createjs.Sound.play("shitou");
			        break;
			    case 3://水晶+5s
			        _gameTimeNum += 500;
			        document.getElementById("stageShow").className = 'stageS3 stageShow';
			        createjs.Sound.play("hongxin");
			        break;
			    case 2://图钉-5s
			        _gameTimeNum -= 500;
			        document.getElementById("stageShow").className = 'stageS4 stageShow';
			        createjs.Sound.play("dingzi");
			        break;
			    case 1://小强+5步
			        _gameScore += 5;
			        document.getElementById("stageShow").className = 'stageS2 stageShow';
			        $('#number span').html(_gameScore +"步");
			        createjs.Sound.play("zhangliang");
			        break;
			}
			timer = setTimeout(function () { document.getElementById("stageShow").className = "" },500);
			_gameBBListIndex++;
			_gameStageIndex++;
			gameLayerMoveNextRow();
			//gameOver();
		}
		return false;
	}
	function createGameLayer(){
		var html = '<div id="GameLayerBG">';
		for(var i=1; i<=2; i++){
			var id = 'GameLayer'+i;
			html += '<div id="'+id+'" class="GameLayer">';
			for(var j=0; j<10; j++ ){
				for(var k=0; k<4; k++){ 
					html += '<div id="'+id+'-'+(k+j*4)+'" num="'+(k+j*4)+'" class="block"></div>';
				}
			}
			html += '</div>';
		}
		html += '</div>';

		return html;
	}
	function closeWelcomeLayer(){
		var l = document.getElementById('welcome');
		l.style.display = 'none';
		$('#scoreTotal').show();
	}
	function showWelcomeLayer(){
		var l = document.getElementById('welcome');
		l.style.display = 'block';
	}
	function showGameScoreLayer(){
		$('#scoreLoading').hide();
		NoStopCtrl.shareText(0, _gameScore);
		setTimeout(function(){
			$('#GameScoreLayer-text').html(infos).show();
		},1000)
		var l = document.getElementById('GameScoreLayer');
		l.style.display = 'block';

		
		if (NoStopCtrl.noStopShow == 1) {
		    var k = document.getElementById('logoShow1');
		    k.className = 'logoShow1 amshow';
		    setTimeout(function () { k.className = 'logoShow1'; }, 1000);
		} else {
		    var k = document.getElementById('logoShow');
		    k.className = 'logoShow3 amshow';
		    setTimeout(function () { k.className = 'logoShow3'; }, 1000);
		}
	}
	function hideGameScoreLayer(){
		var l = document.getElementById('GameScoreLayer');
		l.style.display = 'none';
		$('#timeOver').addClass("hide");
		$('#score').html('0');
		$('#scoreLoading').show();
        $('#GameScoreLayer-text').html('').hide();
	}
	function backBtn(){
		gameRestart();
		hideGameScoreLayer();
		showWelcomeLayer();
	}
	function toStr(obj) {
		if ( typeof obj == 'object' ) {
			return JSON.stringify(obj);
		} else {
			return obj;
		}
		return '';
	}
	var b = createGameLayer();
	document.write(createGameLayer());
	var a = 1;


	//function setSB(v, el) {
	//    var ie5 = (document.all && document.getElementsByTagName);
	//    if (ie5 || document.readyState == "complete") {
	//        //document.getElementById("loadingword").innerText = v + "%";
	//        filterEl = el.children[0];
	//        valueEl = el.children[1];
	//        filterEl.style.width = v * 0.7 + "%";
	//        valueEl.innerText = v + "%";
	//    }
	//}
	//function fakeProgress(v, el) {
	//    if (v > 100) {
	//        //$("#loadingword").show();
	//        //$("#loadingwords").show();
	//        document.getElementById("gameStart").style.opacity = 0;
	//        setTimeout(function () { $("#gameStart").hide() }, 0);
	//        $("#welcome").fadeToggle("slow");
	//    }
	//    else {
	//        setSB(v, el);
	//        window.setTimeout("fakeProgress(" + (++v) + ", document.all['" + el.id + "'])", 20);
	//    }
	//}

	//window.onload = function () {
	//    fakeProgress(0, sb);
	//}
